package com.logicwin.aibala.ui.screens.screenmain;

import java.util.List;

import com.logicwin.aibala.LoadingActivity;
import com.logicwin.aibala.R;
import com.logicwin.aibala.detailPackActivity.DetailDesc;
import com.logicwin.aibala.model.androidSWInfo.APKListItem;
import com.logicwin.aibala.model.androidSWInfo.APKRecommend;
import com.logicwin.aibala.model.androidSWInfo.AndroidSWInfoService;
import com.logicwin.aibala.services.file.AsyncImage;
import com.logicwin.aibala.utils.MyLog;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ApkAdapterIndex extends ApkPackageAdapter{	
	private final String tag= "ApkAdapterIndex";
	private Context context = null;
	
	public ApkAdapterIndex(Activity activity, List<APKListItem> apkList, String type, String sort) {
		super(activity, apkList, type , sort);
		context = activity;
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		if(position == 0) return null;
		return super.getItem(position-1);
		//return null;
	}
	
	public int getCount() {
		if (mApkList==null)
			return 0;
		return mApkList.size() + 1;
	}
	
	public View getView(int position, View convertView, ViewGroup parent) {
		ScreenHome.getViewCount++;
		MyLog.info(tag, "getView ScreenHome.getViewCount="+ScreenHome.getViewCount);
		
		if (!ScreenHome.mCurrentType.equals(AndroidSWInfoService.CLASS_ID_INDEX))
			return convertView;
		
		View view = convertView;
		APKListItem item;
		
		if(position == 0) {
			view = this.getParentActivity().getLayoutInflater().inflate(R.layout.ad, null);
//			return view;
			Gallery g = (Gallery) view.findViewById(R.id.gallery_recommend_home);
	        // Set the adapter to our custom adapter (below)
	        g.setAdapter(new ImageAdapter(context));
	        
	        // Set a item click listener, and just Toast the clicked position
	        g.setOnItemClickListener(new OnItemClickListener() {
	            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//	                Toast.makeText(Gallery1.this, "" + position, Toast.LENGTH_SHORT).show();

	        		Intent intent = new Intent(mParentActivity, DetailDesc.class);
	        		intent.putExtra("apkId", Integer.parseInt(APKRecommend.getRecommendSoftId(position)));
	        		mParentActivity.startActivity(intent);
	            }
	        });
	        return view;
		}		
		else 
		{	
			view = this.getParentActivity().getLayoutInflater().inflate(R.layout.package_item, null);
//			if(position <= 0) return view;
			
			if ((item = this.getCurrApkList().get(position - 1)) == null) {
				return view;
			}
			
			inflateItemView(view, item);
			
			Button btnDownload = (Button) view.findViewById(R.id.package_download);
			btnDownload.setOnClickListener(new ListViewItemButtonClickListener(item,"download"));
			
			Button btnCancel = (Button) view.findViewById(R.id.package_cancel);
			btnCancel.setVisibility(Button.INVISIBLE);
			btnCancel.setOnClickListener(new ListViewItemButtonClickListener(item,"cancel"));
			return view;	
		}
	}
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if(position == 0) return;
		// TODO Auto-generated method stub
		Log.i("ApkPackageAdapter", mApkList.get(position-1).getAPKName());
		Intent intent = new Intent(mParentActivity, DetailDesc.class);

		intent.putExtra("apkId", mApkList.get(position-1).getID());
		mParentActivity.startActivity(intent);

	}	
	
	public class ImageAdapter extends BaseAdapter {
        private static final int ITEM_WIDTH = 322;
        private static final int ITEM_HEIGHT = 130;

        private final int mGalleryItemBackground;
        private final Context mContext;


        private final float mDensity;

        public ImageAdapter(Context c) {
            mContext = c;
            // See res/values/attrs.xml for the <declare-styleable> that defines
            // Gallery1.
            TypedArray a = c.obtainStyledAttributes(R.styleable.Gallery1);
            mGalleryItemBackground = a.getResourceId(
                    R.styleable.Gallery1_android_galleryItemBackground, 0);
            a.recycle();

            mDensity = c.getResources().getDisplayMetrics().density;
        }

        public int getCount() {
            return APKRecommend.listCount();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;

            if (convertView == null) {
                convertView = new ImageView(mContext);

                imageView = (ImageView) convertView;
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                imageView.setLayoutParams(new Gallery.LayoutParams(
                        (int) (ITEM_WIDTH * mDensity + 0.5f),
                        (int) (ITEM_HEIGHT * mDensity + 0.5f)));
            
                // The preferred Gallery item background
                imageView.setBackgroundResource(mGalleryItemBackground);
            } else {
                imageView = (ImageView) convertView;
            }
            
            final ImageView temp = imageView;
            Bitmap cacheImage = AsyncImage.asyncLoadIconImage(APKRecommend.getRecommendImage(position), new AsyncImage.ImageCallback() {
				// 请参见实现：如果第一次加载url时下面方法会执行
				public void imageLoaded(Bitmap image) {
					temp.setImageBitmap(image);
				}
			});
			if (cacheImage != null) {
				temp.setImageBitmap(cacheImage);
			}
			else {
				temp.setImageResource(R.drawable.image);
			}

            return temp;
        }
    }
}
